<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryRef" :inline="true" label-width="68px">
      <el-form-item label="商家名称" prop="deptName">
        <el-input v-model="queryParams.deptName" placeholder="请输入商家名称" clearable style="width: 240px"
          @keyup.enter="handleQuery" />
      </el-form-item>
      <el-form-item label="创建时间" style="width: 308px">
        <el-date-picker v-model="dateRange" value-format="YYYY-MM-DD" type="daterange" range-separator="-"
          start-placeholder="开始日期" end-placeholder="结束日期"></el-date-picker>
      </el-form-item>
      <el-form-item label="更新时间" style="width: 308px">
        <el-date-picker v-model="dateRange" value-format="YYYY-MM-DD" type="daterange" range-separator="-"
          start-placeholder="开始日期" end-placeholder="结束日期"></el-date-picker>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
        <el-button icon="Refresh" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>
    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button type="primary" plain icon="Plus" @click="handleAdd" v-hasPermi="['system:role:add']">新增</el-button>
      </el-col>
      <!-- <el-col :span="1.5">
        <el-button type="danger" plain icon="Delete" :disabled="multiple" @click="handleDelete"
          v-hasPermi="['system:role:remove']">删除</el-button>
      </el-col> -->
      <el-col :span="1.5">
        <el-button type="warning" plain icon="Download" @click="handleExport"
          v-hasPermi="['system:role:export']">导出</el-button>
      </el-col>
    </el-row>

    <!-- 表格数据 -->
    <el-table v-if="refreshTable" v-loading="loading" :data="list" row-key="deptId" :default-expand-all="isExpandAll"
      :tree-props="{ children: 'children', hasChildren: 'hasChildren' }">
      <!-- <el-table-column type="selection" width="55" align="center" /> -->
      <el-table-column label="商家名称" prop="deptName" />
      <el-table-column label="负责人" prop="leader" />
      <el-table-column label="联系电话" prop="phone" />
      <el-table-column label="描述" prop="remark" :show-overflow-tooltip="true" />
      <el-table-column label="详细地址" prop="roleKey" :show-overflow-tooltip="true" />
      <el-table-column label="创建时间" align="center" prop="createTime">
        <template #default="scope">
          <span>{{ parseTime(scope.row.createTime) }}</span>
        </template>
      </el-table-column>
      <el-table-column label="更新时间" align="center" prop="updateTime">
        <template #default="scope">
          <span>{{ parseTime(scope.row.updateTime) }}</span>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template #default="scope">
          <el-button link type="primary" @click="handleSearch(scope.row)"
            v-hasPermi="['system:role:detail']">详情</el-button>
          <el-button link type="primary" @click="handleUpdate(scope.row)"
            v-hasPermi="['system:role:edit']">修改</el-button>
          <el-button link type="primary" @click="handleDelete(scope.row)"
            v-hasPermi="['system:role:remove']">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination v-show="total > 0" :total="total" v-model:page="queryParams.pageNum"
      v-model:limit="queryParams.pageSize" @pagination="getList" />

    <!-- 添加或修改部门对话框 -->
    <el-dialog :title="title" v-model="open" width="600px" append-to-body>
      <el-form ref="deptRef" :model="form" :rules="rules" label-width="80px" :disabled="disabled">

        <el-form-item label="上级商家" prop="parentId" v-if="form.parentId !== 0">
          <el-tree-select v-model="form.parentId" :data="deptOptions" default-expand-all
            :props="{ value: 'deptId', label: 'deptName', children: 'children' }" value-key="deptId"
            placeholder="选择上级商家" check-strictly />
        </el-form-item>

        <el-form-item label="商家名称" prop="deptName">
          <el-input v-model="form.deptName" placeholder="请输入商家名称" />
        </el-form-item>

        <el-form-item label="负责人" prop="leader">
          <el-input v-model="form.leader" placeholder="请输入负责人" maxlength="20" />
        </el-form-item>

        <el-form-item label="联系电话" prop="phone">
          <el-input v-model="form.phone" placeholder="请输入联系电话" maxlength="11" />
        </el-form-item>

        <el-form-item label="详细地址" prop="address">
          <el-input v-model="form.address" placeholder="请输入详细地址" />
        </el-form-item>

        <!-- <el-form-item label="邮箱" prop="email">
          <el-input v-model="form.email" placeholder="请输入邮箱" maxlength="50" />
        </el-form-item> -->

        <el-form-item label="商家图片" prop="imgUrl">
          <image-upload :limit="1" :fileSize="10" v-model:modelValue="form.imgUrl" />
        </el-form-item>

        <el-form-item label="活动图" prop="activeUrl">
          <image-upload :limit="5" :fileSize="10" v-model:modelValue="form.activeUrl" />
        </el-form-item>

        <el-form-item label="商家描述" prop="description">
          <el-input v-model="form.description" :rows="3" :show-word-limit="true" :maxlength="300" type="textarea"
            placeholder="请输入商家描述" />
        </el-form-item>

        <!-- <el-form-item label="部门状态">
              <el-radio-group v-model="form.status">
                <el-radio v-for="dict in sys_normal_disable" :key="dict.value" :value="dict.value">{{ dict.label
                  }}</el-radio>
              </el-radio-group>
            </el-form-item> -->
      </el-form>
      <template #footer>
        <div class="dialog-footer" v-if="!disabled">
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="Merchant">
import { listDept, getDept, delDept, addDept, updateDept, listDeptExcludeChild } from "@/api/system/dept";

const router = useRouter();
const { proxy } = getCurrentInstance();
// const { sys_normal_disable } = proxy.useDict("sys_normal_disable");

const list = ref([]);
const open = ref(false);
const loading = ref(true);
const multiple = ref(true);
const total = ref(0);
const title = ref("");
const dateRange = ref([]);
const isExpandAll = ref(true);
const refreshTable = ref(true);
const deptOptions = ref([]);
const deptRef = ref(null);
const disabled = ref(false);

const data = reactive({
  form: {},
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    deptName: undefined,
    roleKey: undefined,
    status: undefined
  },
  rules: {
    parentId: [{ required: true, message: "上级商家不能为空", trigger: "blur" }],
    deptName: [{ required: true, message: "商家名称不能为空", trigger: "blur" }],
    // orderNum: [{ required: true, message: "显示排序不能为空", trigger: "blur" }],
    email: [{ type: "email", message: "请输入正确的邮箱地址", trigger: ["blur", "change"] }],
    leader: [{ required: true, message: "负责人不能为空", trigger: "blur" }],
    phone: [
      { required: true, message: "手机号不能为空", trigger: "blur" },
      { pattern: /^1[3|4|5|6|7|8|9][0-9]\d{8}$/, message: "请输入正确的手机号码", trigger: "blur" }
    ],
    address: [{ required: true, message: "详细地址不能为空", trigger: "blur" }],
    description: [{ required: true, message: "商家描述不能为空", trigger: "blur" }],
    imgUrl: [{ required: true, message: "商家图片不能为空", trigger: "blur" }]
  },
});

const { queryParams, form, rules } = toRefs(data);

/** 查询角色列表 */
async function getList() {
  loading.value = true;
  const { code, data } = await listDept(proxy.addDateRange(queryParams.value, dateRange.value))
  if (code === 200) {
    list.value = proxy.handleTree(data, "deptId");
    loading.value = false
  }
}

/** 搜索按钮操作 */
function handleQuery() {
  queryParams.value.pageNum = 1;
  getList();
}

/** 重置按钮操作 */
function resetQuery() {
  dateRange.value = [];
  proxy.resetForm("queryRef");
  handleQuery();
}

/** 删除按钮操作 */
function handleDelete(row) {
  proxy.$modal.confirm('是否确认删除名称为"' + row.deptName + '"的数据项?').then(function () {
    return delDept(row.deptId);
  }).then(() => {
    getList();
    proxy.$modal.msgSuccess("删除成功");
  }).catch(() => { });
}

/** 导出按钮操作 */
function handleExport() {
  proxy.download("system/role/export", {
    ...queryParams.value,
  }, `role_${new Date().getTime()}.xlsx`);
}


/** 重置新增的表单以及其他数据  */
function reset() {
  form.value = {
    parentId: '',
    deptName: '',
    leader: '',
    phone: '',
    email: '',
    address: '',
    remark: ''
  };
  proxy.resetForm("deptRef");
}

/** 添加商家信息 */
function handleAdd() {
  reset();
  // getMenuTreeselect();
  open.value = true;
  listDept().then(response => {
    deptOptions.value = proxy.handleTree(response.data, "deptId");
  });
  title.value = "新增商家信息";
}

/** 修改商家信息 */
function handleUpdate(row) {
  reset();
  listDeptExcludeChild(row.deptId).then(response => {
    deptOptions.value = proxy.handleTree(response.data, "deptId");
  });
  getDept(row.deptId).then(response => {
    form.value = response.data;
    open.value = true;
    disabled.value = disabled.value && false
    title.value = "商家信息修改";
  });
}

/** 查看商家信息 */
function handleSearch(row) {
  reset();
  listDeptExcludeChild(row.deptId).then(response => {
    deptOptions.value = proxy.handleTree(response.data, "deptId");
  });
  getDept(row.deptId).then(response => {
    form.value = response.data;
    open.value = true;
    title.value = "商家信息";
    disabled.value = true
  });
}

/** 提交按钮 */
function submitForm() {
  proxy.$refs["deptRef"].validate(valid => {
    console.log('valid========', valid)
    if (valid) {
      if (form.value.deptId != undefined) {
        updateDept(form.value).then(response => {
          proxy.$modal.msgSuccess("修改成功");
          open.value = false;
          getList();
        });
      } else {
        addDept(form.value).then(response => {
          proxy.$modal.msgSuccess("新增成功");
          open.value = false;
          getList();
        });
      }
    }
  });
}

/** 取消按钮 */
function cancel() {
  open.value = false;
  reset();
}


getList();
</script>
